<?php
namespace app\api\model;

use think\Model;
use think\db;

class Shopregion extends Model
{
    public function index()
    {
        error_reporting(0);
        //查出所有的市，并按照区的总数多少降序排列
        $shi = Db::name('shopregion')->alias('a')->join('agency b','a.agencyid=b.id','left')->group('shi')->field('shi,qu,count(qu) as qus ')->where(['b.state'=>1])->order('qus asc')->select();
        for($a=0;$a<count($shi);$a++)
        {
            //根据市名，查出当前市的所有区
            $info[$a]['shi']= $city = $shi[$a]['shi'];  //将市名存进 $info 数组中
            $qu = Db::name('shopregion')->alias('a')->join('agency b','a.agencyid=b.id','left')->group('shi,qu')->field('qu,count(agencyid) as agencyids')->where(['shi'=>$city,'b.state'=>1])->order('agencyids asc')->select();
            for($b=0;$b<count($qu);$b++)
            {
                //根据当前区，查出当天区的所有店铺id
                $info[$a][$b]['qu'] = $quu = $qu[$b]['qu'];  //将区名存进 $info 数组中
                $agencyids = Db::name('shopregion')->alias('a')->join('agency b','a.agencyid=b.id','left')->group('shi,qu,agencyid')->field('agencyid')->where(['qu'=>$quu,'b.state'=>1])->order('agencyid desc')->select();
                //根据店铺id，查出店铺的名称
                for($c=0;$c<count($agencyids);$c++)
                {
                    $agencyid =  $agencyids[$c]['agencyid'];
                    $agencyname = Db::name('agency')->field('id,shop')->where(['id'=>$agencyid,'state'=>1])->select();
                    $shop[$c]['shopid'] = $agencyname[0]['id'];
                    $shop[$c]['shopname'] = $shopname = $agencyname[0]['shop'];
                }
                $info[$a][$b]['shopname'] = $shop;
            }
        }
        $infos = array_reverse($info);
        return $infos;
    }
}